package com.gujiangbo.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 测试类
 */
public class StringEventTestClient {

    public static void main(String[] args) throws InterruptedException {
        /**
         * 1. 创建一个线程工厂提供线程来触发Consumer的事件处理
         */
        ThreadFactory threadFactory = Executors.defaultThreadFactory();

        /**
         * 2. 创建工厂
         */
        StringEventFactory eventFactory = new StringEventFactory();
        /**
         * 3. 创建ringBuffer大小，一定要是2的N次方
         */
        int ringBufferSize = 32;
        /**
         * 4. 创建disruptor
         */
        Disruptor<StringEvent> disruptor = new Disruptor<StringEvent>(
                eventFactory,// 事件工厂
                ringBufferSize,//环形数组大小
                threadFactory,//线程工厂
                ProducerType.MULTI, // 生产者模式 MULTI：多个 ，SINGLE 单个
                new YieldingWaitStrategy()//等待策略
        );
        /**
         * 5. 连接消费端方法
         */
        disruptor.handleEventsWith(new StringEventHandler());
        /**
         * 6. 启动
         */
        disruptor.start();
        /**************以上代码是启动消费者*************/

        /**************以下代码时创建生产者*************/

        /**
         * 7. 创建RingBuffer容器
         */
        RingBuffer<StringEvent> ringBuffer = disruptor.getRingBuffer();

        /**
         * 8. 创建生产者
         */
        StringEventProducer producer = new StringEventProducer(ringBuffer);

        /**
         * 生产数据，往RingBuffer环形数组中放入数据
         */
        for (int i = 0; i < 300000; i++) {
            producer.onData(String.valueOf(i));
        }

        /**
         * 9. 关闭disruptor和executor
         */
        disruptor.shutdown();

    }
}
